var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

var App = angular.module('App', ['underscore']);

App.controller('TestCtrl', function($scope) {
  $scope.items = ['a', 'b', 'c'];
  $scope.add = function() {
    $scope.items.push('z');
  }
});

App.controller('FormBuilderCtrl', function($scope, _) {
  var vm = this;
  // record the current selected cell info
  vm.selectedElement = {
    sectionIndex: 0,
    gridIndex: 0,
    cell: ''
  };

  vm.reload = reload;
  vm.getSelectedGrid = getSelectedGrid;
  vm.getRows = getRows;
  vm.getColumns = getColumns;
  vm.getTrs = getTrs;
  vm.getCellsByRow = getCellsByRow;
  vm.selectedCell = selectedCell;
  vm.addCol = addCol;
  vm.addRow = addRow;
  vm.addRow2 = addRow2;
  vm.removeRow = removeRow;
  vm.removeCol = removeCol;
  vm.expandCell = expandCell;

  function init() {
    // get data from backend
    vm.data = {
      "Sections": [{
        "Title": "11111",
        "HelpDescription": "11",
        "PageBreakBefore": false,
        "Grids": [{
          "Rows": 3,
          "Columns": 2,
          "Cells": [{
            "AttributeId": null,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 1,
            "IsReadOnly": false,
            "IsRequired": false,
            "IsVisible": false,
            "IsEnabled": false,
            "FormRules": []
          }, {
            "AttributeId": null,
            "RowSpan": 2,
            "XPosition": 2,
            "YPosition": 1,
            "IsReadOnly": false,
            "IsRequired": false,
            "IsVisible": false,
            "IsEnabled": false,
            "FormRules": []
          }, {
            "AttributeId": null,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 2,
            "IsReadOnly": false,
            "IsRequired": false,
            "IsVisible": false,
            "IsEnabled": false,
            "FormRules": []
          }, {
            "AttributeId": null,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 3,
            "IsReadOnly": false,
            "IsRequired": false,
            "IsVisible": false,
            "IsEnabled": false,
            "FormRules": []
          }, {
            "AttributeId": null,
            "RowSpan": 1,
            "XPosition": 2,
            "YPosition": 3,
            "IsReadOnly": false,
            "IsRequired": false,
            "IsVisible": false,
            "IsEnabled": false,
            "FormRules": []
          }],
          "XPosition": 0,
          "YPosition": 1,
          "IsReadOnly": false,
          "IsRequired": false,
          "IsVisible": false,
          "IsEnabled": false,
          "FormRules": []
        }],
        "XPosition": 0,
        "YPosition": 1,
        "IsReadOnly": false,
        "IsRequired": false,
        "IsVisible": false,
        "IsEnabled": false,
        "FormRules": []
      }],
      "status": 200,
      "errors": null
    };
    vm.getTrs();
  }

  init();




  function reload() {
    vm.data = {
      "Sections": [{
        "Title": "Section 1",
        "HelpDescription": "string",
        "PageBreakBefore": false,
        "Grids": [{
          "Rows": 4,
          "Columns": 4,
          "Cells": [{
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 1,
            "IsReadOnly": true,
            "title": "1-1"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 2,
            "YPosition": 1,
            "IsReadOnly": true,
            "title": "2-1"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 3,
            "YPosition": 1,
            "IsReadOnly": true,
            "title": "3-1"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 4,
            "YPosition": 1,
            "IsReadOnly": true,
            "title": "4-1"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 2,
            "IsReadOnly": true,
            "title": "1-2"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 2,
            "YPosition": 2,
            "IsReadOnly": true,
            "title": "2-2"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 3,
            "YPosition": 2,
            "IsReadOnly": true,
            "title": "3-2"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 4,
            "YPosition": 2,
            "IsReadOnly": true,
            "title": "4-2"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 3,
            "IsReadOnly": true,
            "title": "1-3"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 2,
            "YPosition": 3,
            "IsReadOnly": true,
            "title": "2-3"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 3,
            "YPosition": 3,
            "IsReadOnly": true,
            "title": "3-3"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 4,
            "YPosition": 3,
            "IsReadOnly": true,
            "title": "4-3"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 1,
            "YPosition": 4,
            "IsReadOnly": true,
            "title": "1-4"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 2,
            "YPosition": 4,
            "IsReadOnly": true,
            "title": "2-4"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 3,
            "YPosition": 4,
            "IsReadOnly": true,
            "title": "3-4"
          }, {
            "AttributeId": 2,
            "RowSpan": 1,
            "XPosition": 4,
            "YPosition": 4,
            "IsReadOnly": true,
            "title": "4-4"
          }],
          "XPosition": 0,
          "YPosition": 1,
          "IsReadOnly": true
        }],
        "XPosition": 0,
        "YPosition": 1,
        "IsReadOnly": true
      }]
    };
  }

  function getSelectedGrid() {
    return vm.data.Sections[vm.selectedElement.sectionIndex].Grids[vm.selectedElement.gridIndex];
  }

  function getRows() {
    return vm.getSelectedGrid().Rows;
  }

  function getColumns() {
    return vm.getSelectedGrid().Columns;
  }

  function getTrs() {
    var rows = vm.getRows();
    //vm.repeatRows = new Array(rows);
    vm.dataCells  = {};
    vm.cells = vm.getSelectedGrid().Cells;
    for (var i = 0; i < rows; i++) {
      vm.dataCells[i] =  _.where(vm.cells, {
        YPosition: i+1
      });
    }
    console.log(vm.dataCells)
    return vm.dataCells;
    
  }

  function selectedCell(cell) {
    G('[getCell]:');
    G(cell);
    var rows = vm.getRows();
    vm.selected = cell;
    vm.selectedElement['cell'] = cell;
    vm.isExpand = (rows == cell.YPosition) ? true : false;
  }

  function getCellsByRow(index) {

  }

  //TODO 限制总数 根据第一行的td数量
  function addCol() {
    var grid = vm.getSelectedGrid();
    var rows = grid.Rows;
    var columns = grid.Columns;
    grid.Columns += 1;
    for (var i = 1; i <= rows; i++) {
      grid.Cells.push({
        "AttributeId": 2,
        "RowSpan": 1,
        "XPosition": columns + 1,
        "YPosition": i,
        "IsReadOnly": true,
        "IsRequired": true,
        "IsVisible": true,
        "IsEnabled": true,
        "title": (columns + 1) + '-' + i
      });
    }
  }

  function addRow(span) {
    var grid       = vm.getSelectedGrid();
    var gridRows    = grid.Rows;
    var gridColumns  = grid.Columns;
    grid.Rows += 1;
    var selectedCell = vm.selectedElement.cell;
    var rowIndex = selectedCell.RowSpan + selectedCell.YPosition;
    // if (span) {
    //   rowIndex = rowIndex + 1;
    // }
    // 判断是否是末行
    if ((selectedCell.YPosition == gridRows && selectedCell.RowSpan == 1) 
       || (selectedCell.RowSpan > 1 && selectedCell.RowSpan + selectedCell.YPosition - 1 == gridRows)){
    }else {
      angular.forEach(grid.Cells, function(cell) {
        if (cell.YPosition >= rowIndex) {
          cell.YPosition = cell.YPosition + 1;
          cell.title = cell.XPosition + '-' + (cell.YPosition);
        }

        // cell expend
        if  ( cell.RowSpan > 1  ) {
          if (cell.XPosition != selectedCell.XPosition && 
              (cell.RowSpan + cell.YPosition > selectedCell.RowSpan + selectedCell.YPosition)) {
            cell.RowSpan += 1;
            gridColumns -= 1; 
          } 
        }
      });     
    }
    
    


    if(gridColumns == 0){
      gridColumns = 1;
    }
    for (var i = 1; i <= gridColumns; i++) {
      grid.Cells.push({
        "AttributeId": 2,
        "RowSpan": 1,
        "XPosition": i,
        "YPosition": rowIndex,
        "IsReadOnly": true,
        "title": i + '--' + (rowIndex)
      });
    }
  }

  function addRow2() {
    var grid = vm.getSelectedGrid();
    var rows = grid.Rows;
    var columns = grid.Columns;
    grid.Rows += 1;
    for (var i = 1; i <= columns; i++) {
      grid.Cells.push({
        "AttributeId": 2,
        "RowSpan": 1,
        "XPosition": i,
        "YPosition": rows + 1,
        "IsReadOnly": true,
        "IsRequired": true,
        "IsVisible": true,
        "IsEnabled": true,
        "title": i + '-' + (rows + 1)
      });
    }
  }

  function removeRow() {
    var grid = vm.getSelectedGrid();
    var cells = grid.Cells;
    var rows = grid.Rows;

    if (grid.Rows > 1) {
      grid.Rows -= 1;
      grid.Cells = _.filter(cells, function(cell) {
        return cell.YPosition != rows;
      })
    }
  }

  function removeCol() {
    var grid   = vm.getSelectedGrid();
    var cells  = grid.Cells;
    var columns = grid.Columns;
    var selectedCell    = vm.selectedElement.cell;
    var removedXposition = selectedCell.XPosition;
    if (grid.Columns > 1) {
      grid.Columns -= 1;
      var newCells = [];
      angular.forEach(grid.Cells, function(cell) {
        if(cell.XPosition != removedXposition){
          if(cell.XPosition > removedXposition) {
            cell.XPosition -= 1;
            resetCellTitle(cell);
          }
          newCells.push(cell);
        }
      });
      grid.Cells = newCells;
    }
  }

  // 1. 只能对当前所选td向下方expand， 最后一排不能expand，即YPosition不能等于Rows
  // 2. 发生合并的td，为该td添加rowspan属性，值为同列下方td的rowspan之和+所选的YPosition

  function expandCell() {
    var grid = vm.getSelectedGrid();
    var cells = grid.Cells;
    var selectedCell = vm.selectedElement.cell;
    var rowspan = selectedCell.RowSpan;
    if (selectedCell.YPosition == grid.Rows || rowspan + selectedCell.YPosition > grid.Rows) {
      alert('Can not expand!')
      return;
    }
    // below cell
    var yPositionofBelowCell = selectedCell.RowSpan > 1 ? selectedCell.YPosition + selectedCell.RowSpan : selectedCell.YPosition + 1;

    G('below cell：' + selectedCell.XPosition + "-" + yPositionofBelowCell);

    // get rowspan number of the selected cell's below cell
    var rowspanOfBelowCell = angular.element("td[position='" + selectedCell.XPosition + "-" + yPositionofBelowCell + "']").attr("rowspan") * 1;

    // update rowspan
    grid.Cells = _.map(cells, function(cell, index, list) {
      if (cell.XPosition == selectedCell.XPosition &&
        cell.YPosition == selectedCell.YPosition) {
        cell.RowSpan += rowspanOfBelowCell;
      }
      // remove the below cell 
      if (cell.XPosition == selectedCell.XPosition &&
        cell.YPosition == selectedCell.YPosition + rowspan) {
        cell = '';
      }
      return cell;
    });
    // remove empty cell
    grid.Cells = _.compact(grid.Cells);

    // grid.Cells = _.reject(cells, function(cell) {
    //   return cell.XPosition == selectedCell.XPosition &&
    //     cell.YPosition == selectedCell.YPosition + rowspan;
    // });
  }

  function G(str) {
    return console.log(str)
  }

  function getSelectedCellDom() {
    // TODO which the cell in section / grid
    return angular.element("td.selected");
  }

  function resetCellTitle(cell){
    if(cell.XPosition && cell.YPosition){
      cell.title = cell.XPosition +'-'+ cell.YPosition;
    }
  }

});



App.directive('formCell', function($compile){
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    templateUrl: 'tpl/form-cell.html',
    link: function(scope, elem, attrs) {
      console.log('~~');
    },
    compile: function(element, attr) {
        console.log(element);
    }
  }
})



App.directive('myDirective', function() {
  return {
    scope: {
      index: '=',
      item: '=myDirective'
    },
    link: function(scope, elem, attrs, $index) {
      elem.html(scope.item)
      elem.bind('click', function($index) {
        alert(scope.index);
      });
    }
  };
});